/*
 * sgutil.c
 *
 *  Created on: 2010. 9. 11.
 *      Author: wanderer
 */

#include "sgutil.h"

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <stdarg.h>

#define SG_BUF_MAX	256

const char *_sgLineFormat = "%-10s%s\n";

SG_LOG_LEVEL _level = SG_LOG_INFO;

char *_sgGetLogTag(SG_LOG_LEVEL level);
char *_sgGetLineInfo(const char *file, const int line, const char *func);

char *_sgGetLogTag(SG_LOG_LEVEL level) {
	static char buf[SG_BUF_MAX] = { 0 };
	switch (level) {
	case SG_LOG_DEBUG:
		snprintf(buf, SG_BUF_MAX - 1, "Debug");
		break;
	case SG_LOG_INFO:
		snprintf(buf, SG_BUF_MAX - 1, "Info");
		break;
	case SG_LOG_WARN:
		snprintf(buf, SG_BUF_MAX - 1, "Warn");
		break;
	case SG_LOG_ERROR:
		snprintf(buf, SG_BUF_MAX - 1, "Error");
		break;
	case SG_LOG_FATAL:
		snprintf(buf, SG_BUF_MAX - 1, "Fatal");
		break;
	default:
		snprintf(buf, SG_BUF_MAX - 1, "Unknown");
	}
	return buf;
}

char *_sgGetLineInfo(const char *file, const int line, const char *func) {
	static char buf[SG_BUF_MAX] = { 0 };
	snprintf(buf, SG_BUF_MAX - 1, "%s ( %d ) : %s", file, line, func);
	return buf;
}

void __sgSetLogLevel(SG_LOG_LEVEL level) {
	_level = level;
}

void __sgAssert(const char *file, const int line, const char *func,
		const char *cond, const char *template, ...) {

	if (SG_ASSERT_LEVEL >= _level) {

		char buf[SG_BUF_MAX] = { 0 };
		va_list argptr;
		va_start(argptr, template);
		vsnprintf(buf, SG_BUF_MAX - 1, template, argptr);
		va_end(argptr);

		printf("\n");
		printf(_sgLineFormat, "Assert", _sgGetLineInfo(file, line, func));
		printf(_sgLineFormat, "Condition", cond);
		printf(_sgLineFormat, "Message", buf);
		printf("\n");
	}
}

void __sgLogMessage(const char *file, const int line, const char *func,
		SG_LOG_LEVEL level, const char *template, ...) {
	if (level >= _level) {

		char buf[SG_BUF_MAX] = { 0 };
		va_list argptr;
		va_start(argptr, template);
		vsnprintf(buf, SG_BUF_MAX - 1, template, argptr);
		va_end(argptr);

		printf("\n");
		printf(_sgLineFormat, _sgGetLogTag(level), _sgGetLineInfo(file, line,
				func));
		printf(_sgLineFormat, "Message", buf);
		printf("\n");
	}
}
